<template>
  <div>
    <el-dialog
      :title="`${titleText[openType]}学生`"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible="open"
      width="650px"
      append-to-body
      @close="cancel"
    >
      <div v-loading="formLoading">
        <el-form
          :model="form"
          ref="studentFormRef"
          size="small"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="学号" prop="studentNum">
            <el-input
              oninput="value=value.replace(/[^a-zA-Z_@0-9]/g, '')"
              @blur="checkStudentNum"
              maxlength="20"
              style="width: 430px"
              show-word-limit
              v-model="form.studentNum"
              :disabled="openType == 2"
              placeholder="请输入学号"
            />
          </el-form-item>
          <el-form-item label="照片" prop="photo">
            <div class="upload_content">
              <!-- 上传图片 -->
              <div v-if="form.photo" class="upload-head" @click="editCropper()">
                <img :src="form.photo" class="cover"/>
              </div>
              <div v-else class="upload-head" @click="editCropper()">
                <div>
                  <img src="@/assets/images/add.png" class="add" alt=""/>
                </div>
                <div>上传图片</div>
              </div>
              <div class="uploadTips">
                建议图片比例5:7，支持jpg、png格式，图片小于5M
              </div>
            </div>
            <vuecut
              :h="280"
              :url="form.photo"
              @coverResult="coverResult"
              title="图片上传"
              :open.sync="vuecutshow"
            ></vuecut>
          </el-form-item>
          <el-form-item label="学生姓名" prop="name">
            <el-input
              style="width: 430px"
              v-model="form.name"
              maxlength="10"
              show-word-limit
              placeholder="请输入学生姓名"
            />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-removeAriaHidden v-model="form.sex">
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="!propsInfo" label="行政班" prop="classArr">
            <el-cascader
              filterable
              collapse-tags
              style="width: 430px"
              v-model="form.classArr"
              placeholder="可搜索：分院/专业/班级"
              :options="treeData"
              clearable
              :props="{
                label: 'name',
                value: 'id',
                children: 'children',
                disabled: 'enabled'
              }"
            >
              <div slot="empty" class="search_empty">
                搜索学生已添加或不存在
              </div>
            </el-cascader>
          </el-form-item>
          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input
              style="width: 430px"
              v-model="form.phoneNumber"
              placeholder="请输入手机号码"
            />
          </el-form-item>
          <el-form-item label="身份证号" prop="idCard">
            <el-input
              style="width: 430px"
              v-model="form.idCard"
              placeholder="请输入身份证号"
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="cancel">取 消</el-button>
        <el-button
          :loading="formLoading"
          v-preventReClick
          type="primary"
          @click="submitForm"
        >确 定
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPost_class } from '@/api/schoolOrganization/organization'
import { formatArrayWithCustomNames } from '@/views/teachIndex/formatOrganizationData'
import {
  getPost_student,
  addPost_student,
  updatePost_student
} from '@/api/schoolOrganization/student'
import { checkidCardnot, checkPhonenot } from '@/utils/validate'
import { getUserlnfoByUsemame } from '@/api/system/user'

export default {
  name: 'updateStudentDialog',
  data() {
    return {
      titleText: {
        1: '添加',
        2: '编辑'
      },
      treeData: [],
      formLoading: false,
      vuecutshow: false,
      form: {
        studentNum: '',
        photo: '',
        name: '',
        phoneNumber: '',
        idCard: '',
        sex: 0,
        classArr: []
      },
      // 表单校验
      rules: {
        classArr: [
          { required: true, message: '请选择班级', trigger: 'change' }
        ],
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        studentNum: [
          { required: true, message: '学号不能为空', trigger: 'blur' }
          // { min: 7, message: "学号长度不能小于7位" },
        ],
        sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
        idCard: [
          { required: false, validator: checkidCardnot, trigger: 'blur' }
        ],
        phoneNumber: [
          { required: false, validator: checkPhonenot, trigger: 'blur' }
        ]
      }
    }
  },
  props: {
    open: {
      type: Boolean,
      default: false
    },
    studentForm: {
      type: [Object],
      default: null
    },
    propsInfo: {
      type: [Object],
      default: null
    },
    openType: {
      type: [String, Number],
      default: 1
    }
  },
  watch: {
    open: {
      handler(val) {
        if (val) {
          this.getStudentList()
          //编辑
          if (this.openType == 2) {
            this.handleEdit()
          } else {
            // 从组织结构添加
            if (this.propsInfo) {
              this.form.classArr = [
                this.propsInfo.branchId,
                this.propsInfo.majorId,
                this.propsInfo.classId
              ]
            }
          }
        }
      }
    }
  },
  methods: {
    async checkStudentNum() {
      if (this.form.studentNum) {
        try {
          let res = await getUserlnfoByUsemame(this.form.studentNum)
          const { code, data } = res
          if (code == 200) {
            if (data) {
              this.$modal.msgWarning(`${data.nickName}已存在`)
              const formobj = JSON.parse(JSON.stringify(this.form))
              this.form = {
                studentNum: data.account,
                photo: data.photo,
                name: data.nickName,
                phoneNumber: data.phoneNumber,
                idCard: data.idCard,
                sex: parseInt(data.sex),
                userId: data.userId,
                studentId: data.studentId,
                classArr: formobj.classArr
              }
            } else {
              this.form.userId = ''
              this.form.studentId = ''
            }
          }
        } catch (e) {
          console.error(e)
        }
      }
    },
    /** 组件返回图片 */
    coverResult(e) {
      this.form.photo = e
    },
    editCropper() {
      this.vuecutshow = true
    },
    async handleEdit() {
      this.formLoading = true
      try {
        const postId = this.studentForm.studentId
        let res = await getPost_student(postId)
        const { code, data } = res
        if (code == 200) {
          this.form = {
            studentNum: data.studentNum,
            photo: data.photo,
            name: data.name,
            phoneNumber: data.phoneNumber,
            idCard: data.idCard,
            sex: parseInt(data.sex),
            userId: data.userId,
            studentId: data.studentId,
            classArr: [data.branchId, data.majorId, data.classId]
          }
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.formLoading = false
      }
    },
    cancel() {
      this.resetForm('studentFormRef')
      this.form = {
        studentNum: '',
        photo: '',
        name: '',
        phoneNumber: '',
        idCard: '',
        sex: 0,
        classArr: []
      }
      this.$emit('update:open', false)
    },
    submitForm() {
      this.$refs.studentFormRef.validate(async(valid) => {
        if (valid) {
          let params = {
            ...this.form,
            branchId: this.form.classArr[0],
            majorId: this.form.classArr[1],
            classId: this.form.classArr[2]
          }
          if (this.openType == 1) {
            params.schoolId = this.$store.getters.schoolId
            this.addStudent(params)
          } else {
            this.updateStudent(params)
          }
        } else {
          return false
        }
      })
    },
    async addStudent(params) {
      const loading = this.$loading({
        lock: true,
        text: '正在添加中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      try {
        let res = await addPost_student(params)
        const { code } = res
        if (code == 200) {
          this.$modal.msgSuccess(`添加成功`)
          this.cancel()
          this.$emit('refresh', true)
        }
      } catch (e) {
        console.error(e)
      } finally {
        loading.close()
      }
    },
    updateStudent(params) {
      const loading = this.$loading({
        lock: true,
        text: '正在处理中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      try {
        this.$confirm(
          `<div style="color: #ea3f26;">
                       <div>更换后：</div>
                       <div>1、学生部分学习中课程（新班级本学期未排课课程）将变更为中止状态；</div>
                       <div>2、小组提交的考核会同步新分组中组长的进度和成绩</div>
                       <div>请谨慎操作</div>
                    </div>`,
          '编辑确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            dangerouslyUseHTMLString: true,
            type: 'warning'
          }
        )
          .then(async() => {
            let res = await updatePost_student(params)
            const { code } = res
            if (code == 200) {
              this.$modal.msgSuccess(`编辑成功`)
              this.cancel()
              this.$emit('refresh', true)
            }
          })
          .catch(() => {
            this.$modal.msgInfo('已取消')
          })
      } catch (e) {
        console.error(e)
      } finally {
        loading.close()
      }
    },
    async getStudentList() {
      try {
        let params = {
          schoolId: this.$store.getters.schoolId,
          pageNum: 1,
          pageSize: 999999
        }
        if (this.$store.getters.roleId == 'branchAdmin') {
          params.branchId = this.$store.getters.branchId
        }
        let res = await listPost_class(params)
        const { code, rows } = res
        if (code == 200) {
          let arr = []
          arr = formatArrayWithCustomNames(rows)
          this.treeData = arr
        }
      } catch (e) {
        console.error(e)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.upload_content {
  display: flex;

  .uploadTips {
    margin-left: 5px;
    height: 212px;
    display: flex;
    align-items: flex-end;
    font-size: 12px;
    font-weight: 400;
    color: #a6a6a6;
  }

  .upload-head {
    width: 152px;
    height: 212px;

    .add {
      width: 29px;
      height: 29px;
      margin: 70px 0 0 0;
    }

    .cover {
      width: 150px;
      height: 210px;
      border-radius: 4px;
    }
  }
}
</style>
